#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author : hai.long
import os
import sys
import json
import socket
import datetime
import requests
from script_to_json.script_convert_json import gen_ts_data
from requests_toolbelt.multipart.encoder import MultipartEncoder


def now():
    now_time = datetime.datetime.now()
    formatted_time = now_time.strftime(f"%Y-%m-%d %H:%M:%S.{now_time.strftime('%f')[:-3]}")  # 格式化输出
    return formatted_time


def get_gen_script_line():
    file_name = 'gen_script'
    base_path = os.path.dirname(os.path.realpath(sys.argv[0]))
    file_path = f"{base_path}/{file_name}.py"
    if os.path.exists(file_path):
        with open(file_path, encoding='utf8') as f:
            text = f.readlines()
            return len(text)
    else:
        return 0


def get_code_line(line):
    file_name = 'gen_script'
    base_path = os.path.dirname(os.path.realpath(sys.argv[0]))
    file_path = f"{base_path}/{file_name}.py"
    if os.path.exists(file_path):
        with open(file_path, encoding='utf8') as f:
            text = f.readlines()
            current_line = len(text)
            if current_line > 10:
                return current_line, text[line]
            else:
                return False, ''
    else:
        return False, ''


def gen_code_to_str(step_line, line):
    c_line, code = get_code_line(line)
    if c_line and len(code) > 0:
        string = gen_ts_data(str(code)[4:-1])
        string["current_line"] = step_line
        string["code"] = 2000
        text = json.dumps(string)
    else:
        text = ''
    return text


def get_local_ip():
    st = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    try:
        st.connect(('10.255.255.255', 1))
        ip = st.getsockname()[0]
    except Exception:
        ip = '127.0.0.1'
    finally:
        st.close()
    return ip


def compare(value1, condition, value2):
    value1, value2 = float(value1), float(value2)
    if condition == "equal":
        return value1 == value2
    elif condition == "not_equal":
        return value1 != value2
    elif condition == "greater_than":
        return value1 > value2
    elif condition == "greater_or_equals":
        return value1 >= value2
    elif condition == "less_than":
        return value1 < value2
    elif condition == "less_or_equals":
        return value1 <= value2
    elif condition == "contains":
        return value1 in value2
    elif condition == "not_contains":
        return value1 not in value2
    else:
        print("!!!!!!!!!!!!!无效的比较符号!!!!!!!!!!!!!!!!")
        print(value1, condition, value2)
        # raise ValueError("无效的比较符号")


class FeiShuTalk(object):
    def __init__(self):
        url = "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal"
        payload = {
            "app_id": "cli_a41391c59831d00c",
            "app_secret": "xL9rvrtk3tA60JpPjVcQChaoFh8NS7Ok"
        }
        res = requests.post(url, json=payload)
        res_data = res.json()
        tenant_access_token = res_data["tenant_access_token"]
        self.headers = {"Authorization": f"Bearer {tenant_access_token}"}

    def download_file(self, file_name, file_token):
        url = f'https://open.feishu.cn/open-apis/drive/v1/files/{file_token}/download'
        response = requests.request("GET", url, headers=self.headers)
        print(response.headers)
        # 检查响应状态码是否为200
        if response.status_code == 200:
            # 将图片二进制数据写入到文件中，即'wb'
            with open(f'files/{file_token}/{file_name}', 'wb') as f:
                f.write(response.content)


def upload_file_to_oss(file_path, file_name):
    url = "https://test.snkoudai.com/api/foundation/fileAccess/upload"
    # 创建一个MultipartEncoder对象，用于拼接form-data内容
    multipart_data = MultipartEncoder(fields={
        "folderPath": "automate/image/",
        "originalFilename": f'{file_name}.jpg',
        "file": (file_path, open(file_path, "rb"), "image/jpeg")
    })
    # 设置请求头，指定Content-Type为multipart/form-data
    headers = {
        "Content-Type": multipart_data.content_type
    }
    # 发送POST请求
    response = requests.post(url, data=multipart_data, headers=headers)
    print("oss文件上传结果：", response.status_code)
    if response.status_code == 200:
        res_json = response.json()
        print("oss文件上传结果：", res_json)
        if res_json["respCode"] == 0:
            return {"status": 1000, "url": res_json["obj"]["internetUrl"]}
    else:
        return {"status": 1001}


def upload_file_to_simple_drawing(file_path, file_name):
    url = "http://124.220.103.163:8083/app/upload.php"
    # 创建一个MultipartEncoder对象，用于拼接form-data内容
    multipart_data = MultipartEncoder(fields={
        "name": file_name,
        "uuid": file_name,
        "sign": str(datetime.datetime.now().timestamp()),
        "file": (file_path, open(file_path, "rb"), "image/jpeg")
    })
    headers = {
        "Content-Type": multipart_data.content_type
    }
    # 发送POST请求
    response = requests.post(url, data=multipart_data, headers=headers, verify=False)
    if response.status_code == 200:
        res_json = response.json()
        print("oss文件上传结果：", res_json)
        if res_json["code"] == 200:
            return {"status": 1000, "url": res_json["url"]}
    else:
        return {"status": 1001}


def file_exists(file_name, file_token):
    file_path = f'files/{file_token}'
    if not os.path.exists(file_path):
        os.makedirs(file_path)
        fs = FeiShuTalk()
        fs.download_file(file_name, file_token)


if __name__ == '__main__':
    upload_file_to_simple_drawing("./20231219-173604.jpg", '20231219-173604')
